﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.ZX.Manager
{
    
	public class TestObject:BaseUnitPoolable<TestObject>
	{
		
	}
    public class PPoolManager : BaseSingleton<PPoolManager>
    {
        private Dictionary<string, object> dictPoolList;
        public PPoolManager() : base()
        { }

        public override void onInit()
        {
            dictPoolList = new Dictionary<string, object>();
        }

        /// <summary>
        /// 创建一个对象池
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="initSize">初始容量</param>
        /// <param name="oneTimeInitFunc">初始化对象回调</param>
        /// <param name="resetAction">回收对象重置回调</param>
        public void CreatePool<T>(int initSize, 
            RefAction<T> clearAction, 
            Func<T, ObjectPool<T>, T> oneTimeInitFunc, 
            Action<T> resetAction = null) 
            where T : BaseUnitPoolable<T>, new()
        {
            if (!dictPoolList.ContainsKey(typeof(T).ToString()))
            {
                ObjectPool<T> tempPool = new ObjectPool<T>(initSize, clearAction, oneTimeInitFunc, resetAction);
                AddPool(tempPool);
            }
        }

        /// <summary>
        /// 获得对应类型对象池
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <returns>对应类型对象池</returns>
        public ObjectPool<T> GetPool<T>() where T : BaseUnitPoolable<T>, new()
        {
            //UnityEngine.Debug.Log(typeof(T).Name);
            string typeName = typeof(T).Name;
            if (dictPoolList.ContainsKey(typeName))
            {
                return dictPoolList[typeName] as ObjectPool<T>;
            }
            else
            {
                return null;
            }
        }


        private void AddPool<T>(ObjectPool<T> targetPool) where T : BaseUnitPoolable<T>, new()
        {
            targetPool.PoolId = dictPoolList.Count();
            dictPoolList.Add(typeof(T).Name, targetPool);
        }

        public void RemovePool<T>() where T : BaseUnitPoolable<T>, new()
        {
            string type = typeof(T).Name;
            if (dictPoolList.ContainsKey(type))
            {
                ObjectPool<T> temp = (ObjectPool<T>)dictPoolList[type];
                temp.Clear();
                dictPoolList.Remove(type);
                //temp = null;
            }
        }

        public void RemoveAll()
        {
            foreach (var item in dictPoolList)
            {
                var temp = dictPoolList[item.Key];
                temp = null;
            }
        }

        public void RecycleObj<T>(T obj) where T : BaseUnitPoolable<T>, new()
        {
            if (GetPool<T>() != null)
            {
                GetPool<T>().RecyleObj(obj.Id);
            }
        }
    }
}
